/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
  if (intervals.length <= 1) return intervals

  //排序
  intervals.sort((a, b) => a[0] - b[0])

  //存入数组intervals的第一个元素
  let result = []
  result.push(intervals[0])

  for (let i = 1; i < intervals.length; i++) {
    let current = intervals[i]
    let lastMerged = result[result.length - 1]

    if (current[0] <= lastMerged[1]) {
      lastMerged[1] = Math.max(current[1], lastMerged[1])
    } else {
      result.push(current)
    }
  }

  //返回
  return result
};

console.log(merge([[1, 3], [8, 10], [2, 6], [15, 18]]))